﻿using System;
using System.Collections.Generic;
using NHibernate;
using SimpleScrum.Core.Entities;
using SimpleScrum.Helpers;

namespace SimpleScrum.Areas.Scrum.Models
{
    public class TeamModel
    {
        private ISession _session;

        public IList<Team> GetTeams()
        {
            IList<Team> teams;
            using (_session = NHibernateHelper.GetSession())
            {
                //NHibernate query 
                IQuery query =
                    _session.CreateQuery("from Team;");
                teams = query.List<Team>();
            }
            return teams;
        }

        public Team GetTeamById(Guid id)
        {
            Team team;
            using (_session = NHibernateHelper.GetSession())
            {
                using (ITransaction tran = _session.BeginTransaction())
                {
                    team = _session.Get<Team>(id);
                    tran.Commit();
                }
            }
            return team;
        }

        public bool NewTeam(Team team)
        {
            using (_session = NHibernateHelper.GetSession())
            {
                using (ITransaction tran = _session.BeginTransaction())
                {
                    _session.Save(team);
                    tran.Commit();
                }
            }
            return true;
        }

        public void UpdateTeam(Team team)
        {
            using (_session = NHibernateHelper.GetSession())
            {
                using (ITransaction tran = _session.BeginTransaction())
                {
                    _session.Update(team);
                    tran.Commit();
                }
            }
        }

        public void DeleteTeam(Team team)
        {
            using (_session = NHibernateHelper.GetSession())
            {
                using (ITransaction tran = _session.BeginTransaction())
                {
                    try
                    {
                        _session.Delete(team);
                        tran.Commit();
                    }
                    catch (Exception ex)
                    {
                        string msg = ex.Message;
                    }
                }
            }
        }
    }
}